package com.net.xpay.alipay.flexible;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.domain.AlipayFundFlexiblestaffingAuthenticationApplyModel;
import com.alipay.api.domain.AlipayFundFlexiblestaffingAuthenticationQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.net.common.util.SerializationUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;


@Slf4j
public class FlexibleAlipayClient {

    private final AlipayClient alipayClient;

    private FlexibleAlipayProperties flexibleAlipayProperties;


    public FlexibleAlipayClient(AlipayClient alipayClient, FlexibleAlipayProperties flexibleAlipayProperties) {
        this.alipayClient = alipayClient;
        this.flexibleAlipayProperties = flexibleAlipayProperties;
    }

    public boolean checkSignV1(Map<String, String> params) throws AlipayApiException {
        return AlipaySignature.verifyV1(params, flexibleAlipayProperties.getAlipayPublicKey(), "UTF-8", "RSA2");
    }

    private <T extends AlipayResponse> T autoRetryExecute(AlipayRequest<T> req) throws AlipayApiException {
        return execute(req);
    }

    public <T extends AlipayResponse> T execute(AlipayRequest<T> req)
            throws AlipayApiException {
        T alipayRsp = alipayClient.execute(req);
        log.info("execute alipayRsp={}", SerializationUtil.obj2String(alipayRsp));
        return alipayRsp;
    }

    private <T extends AlipayResponse> T pageExecute(AlipayRequest<T> req) throws AlipayApiException {
        T alipayRsp = alipayClient.pageExecute(req, "get");
        log.info("pageExecute alipayRsp={}", SerializationUtil.obj2String(alipayRsp));
        if (alipayRsp.isSuccess()) {
            return alipayRsp;
        }
        throw new AlipayApiException(alipayRsp.getSubCode(), alipayRsp.getSubMsg());
    }

    //零工卡人脸验证
    public AlipayFundFlexiblestaffingAuthenticationApplyResponse applyAlipayFundFlexiblestaffingAuthentication(AlipayFundFlexiblestaffingAuthenticationApplyModel model) throws AlipayApiException {
        AlipayFundFlexiblestaffingAuthenticationApplyRequest request = new AlipayFundFlexiblestaffingAuthenticationApplyRequest();

        request.setBizModel(model);

        return autoRetryExecute(request);
    }

    public AlipayFundFlexiblestaffingAuthenticationQueryResponse queryAlipayFundFlexiblestaffingAuthentication(AlipayFundFlexiblestaffingAuthenticationQueryModel model) throws AlipayApiException {
        AlipayFundFlexiblestaffingAuthenticationQueryRequest request = new AlipayFundFlexiblestaffingAuthenticationQueryRequest();

        request.setBizModel(model);

        return autoRetryExecute(request);
    }


}
